from django.shortcuts import render
from rest_framework import viewsets # 视图集模块
from rest_framework.response import Response    # 响应
from .models import *       # 模型类
from .serializers import *  # 所有的序列化器类
from rest_framework.status import HTTP_404_NOT_FOUND,HTTP_201_CREATED,HTTP_204_NO_CONTENT

# Create your views here.

"""
create 创建 list 查询所有 retrieve 查询单条 update 修改 delete 删除
"""

# 视图集
# class StudentsViewset(viewsets.ViewSet):
#     def list(self, request):
#         # 查询Student所有的数据
#         students = Student.objects.all()    # 查询集
#         # 序列化 查询集==》json
#         serializer = StudentSerializer(students, many=True)
#         return Response(serializer.data)
#
#     def create(self, request):
#         # 反序列化 json==>模型对象
#         serializer = StudentSerializer(data=request.data)
#         # 校验
#         serializer.is_valid(raise_exception=True)
#         # 保存
#         serializer.save()
#         # 响应
#         return Response(serializer.data)
#
#     def retrieve(self,request,pk): # 加入pk参数，条件 id=? get
#         try:
#             student = Student.objects.get(id=pk)
#
#         except Student.DoesNotExist:    # 针对于没查询到，没有模型对象才会抛出的异常
#             return Response(status=HTTP_404_NOT_FOUND)
#
#         serializer = StudentSerializer(student)    # 序列化
#         return Response(serializer.data)
#
#     def update(self,request,pk):
#         try:
#             student = Student.objects.get(id=pk)
#
#         except Student.DoesNotExist:    # 针对于没查询到，没有模型对象才会抛出的异常
#             return Response(status=HTTP_404_NOT_FOUND)
#
#         # 反序列化 json==>模型对象
#         # student原数据
#         serializer = StudentSerializer(student, data=request.data)
#         # 校验
#         serializer.is_valid(raise_exception=True)
#         # 保存
#         serializer.save()
#         # 响应
#         return Response(serializer.data)
#
#     def destory(self,request,pk):
#         try:
#             student = Student.objects.get(id=pk)
#
#         except Student.DoesNotExist:    # 针对于没查询到，没有模型对象才会抛出的异常
#             return Response(status=HTTP_404_NOT_FOUND)
#
#         # 删除
#         student.delete()
#         return Response(status=HTTP_204_NO_CONTENT)


class StudentsViewSet(viewsets.ViewSet):
    queryset = Student.objects.filter(is_delete=False)     # 查询集
    serializer_class = StudentSerializer    # 需要使用的序列化器